﻿
using System;

public static class RetCode_PaymentValiedate
{
    public const int Suc = 0;
    public const int ValidateFail = -1;
    public const int CannotFindGoods = -10;
    public const int GoodsCannotBuy = -11;
    public const int httpError = -12;
    public const int InvalidPayType = -13;
}


public class NetHandler_PaymentValidate : GameServerMessageHandler
{
    public const string PaymentValidate_Key = "PaymentValidate";

    public static NetHandler_PaymentValidate NewHandler()
    {
        return new NetHandler_PaymentValidate();
    }

    PaymentValidateData m_VerifyData;
    TCPClient m_Client;

    protected override ISerialize NewData() => new PaymentValidateData();

    public override void _Execute(TCPClient client, ISerialize data)
    {
        PaymentValidateData buy = data as PaymentValidateData;

        m_VerifyData = buy;
        m_Client = client;

        GameDebug.Log($"userid:{client.userID}  clientId:{client.clientId} 请求支付验证：{buy.goodsId}  type:{buy.payType} transactionId:{buy.transactionId}  receipt:{buy.receipt}");

        bool exist  = payment.TransactionExist(client.userID,buy.transactionId);

        if (exist)
        {
            GameDebug.LogError("订单已存在，无法重复验证");
            OnValidateResult(client, RetCode_PaymentValiedate.ValidateFail, "Transaction has aleady exist.", new PaymentValidateData() { goodsId = m_VerifyData.goodsId, productId = m_VerifyData.productId });
            return;
        }

        if (buy.payType == (int)PayType.Google)
        {
            GooglePlayStoreReceiptVerify googlePlayVerify = new GooglePlayStoreReceiptVerify(ServerConfig.GooglePaymentTestMode,  buy.receipt, ServerConfig.packageName, buy.productId, OnGoogleVerifyCallBack);
            googlePlayVerify.Verify();
        }
        else if (buy.payType == (int)PayType.UDP)
        {
            UDPReceiptVerify verify = new UDPReceiptVerify(ServerConfig.UDPPaymentTestMode, buy.receipt, ServerConfig.packageName, buy.productId,ServerConfig.UDPIAPClientId ,ServerConfig.UDPIAPClientSecret,OnUDPVerifyCallBack);
            verify.Verify();
            //GameDebug.Log("UDP 支付先直接给");
            //OnValidateResult(this.m_Client, 0, "", new PaymentValidateData() { goodsId = m_VerifyData.goodsId, productId = m_VerifyData.productId, payType = m_VerifyData.payType, receipt = m_VerifyData.receipt, transactionId = m_VerifyData.transactionId });

        }
        else if (buy.payType == (int)PayType.IOS)
        {
            AppStoreReceiptVerify appleVerify = new AppStoreReceiptVerify(ServerConfig.ApplePaymentTestMode,buy.transactionId,buy.receipt, OnAppleVerifyCallBack);
            appleVerify.Verify();
        }
        else if (buy.payType == (int)PayType.EDITOR)
        {
            OnValidateResult(this.m_Client, 0, "", new PaymentValidateData() { goodsId = m_VerifyData.goodsId, productId = m_VerifyData.productId, payType = m_VerifyData.payType, receipt = m_VerifyData.receipt, transactionId = m_VerifyData.transactionId },false);
        }
        else
        {
            GameDebug.LogError($"不支持的支付类型：{buy.payType}");
            OnValidateResult(client, RetCode_PaymentValiedate.InvalidPayType, "not support pay type", new PaymentValidateData() { goodsId = m_VerifyData.goodsId, productId = m_VerifyData.productId});
        }

        //TODO.验证行为
        //OnValidateResult(client,0,"",new PaymentValidateData() { goodsId = buy.goodsId ,productId = buy.productId,payType = buy.payType,receipt = buy.receipt,transactionId = buy.transactionId });
    }

    private void OnUDPVerifyCallBack(UDPReceiptVerify verify)
    {
        int ret = 0;
        string err = "";
        if (verify.resultStatus == PurchaseVerifyResult.Success)
        {
            ret = RetCode_PaymentValiedate.Suc;
        }
        else if (verify.resultStatus == PurchaseVerifyResult.FakeReceipt)
        {
            ret = RetCode_PaymentValiedate.ValidateFail;
            err = "Receipt valiedate failed";
        }
        else if (verify.resultStatus == PurchaseVerifyResult.HttpRequestError)
        {
            ret = RetCode_PaymentValiedate.httpError;
            err = "network error";
        }
        OnValidateResult(this.m_Client, ret, err, new PaymentValidateData() { goodsId = m_VerifyData.goodsId, productId = m_VerifyData.productId, payType = m_VerifyData.payType, receipt = m_VerifyData.receipt, transactionId = m_VerifyData.transactionId });
    }

    void OnAppleVerifyCallBack(AppStoreReceiptVerify verify)
    {
        int ret = 0;
        string err = "";
        if (verify.resultStatus == AppleReceiptVerifyResult.Success)
        {
            ret = RetCode_PaymentValiedate.Suc;
        }
        else if (verify.resultStatus == AppleReceiptVerifyResult.FakeReceipt)
        {
            ret = RetCode_PaymentValiedate.ValidateFail;
            err = "Receipt valiedate failed";
        }
        else if (verify.resultStatus == AppleReceiptVerifyResult.HttpRequestError)
        {
            ret = RetCode_PaymentValiedate.httpError;
            err = "network error";
        }
        OnValidateResult(this.m_Client, ret, err, new PaymentValidateData() { goodsId = m_VerifyData.goodsId, productId = m_VerifyData.productId, payType = m_VerifyData.payType, receipt = m_VerifyData.receipt, transactionId = m_VerifyData.transactionId });
    }
    void OnGoogleVerifyCallBack(GooglePlayStoreReceiptVerify verify)
    {
        int ret = 0;
        string err = "";
        if (verify.resultStatus == GooglePlayStorePurchaseVerifyResult.Success)
        {
            ret = RetCode_PaymentValiedate.Suc;
        }
        else if (verify.resultStatus == GooglePlayStorePurchaseVerifyResult.FakeReceipt)
        {
            ret = RetCode_PaymentValiedate.ValidateFail;
            err = "Receipt valiedate failed";
        }
        else if (verify.resultStatus == GooglePlayStorePurchaseVerifyResult.HttpRequestError)
        {
            ret = RetCode_PaymentValiedate.httpError;
            err = "network error";
        }
        OnValidateResult(this.m_Client, ret, err, new PaymentValidateData() { goodsId = m_VerifyData.goodsId, productId = m_VerifyData.productId, payType = m_VerifyData.payType, receipt = m_VerifyData.receipt, transactionId = m_VerifyData.transactionId });
    }
   
    void OnValidateResult (TCPClient client, int ret,string failReason, PaymentValidateData validateData,bool save = true)
    {
        int code = ret;
        string err = failReason;

        UserServer userServer = Game.instance.GetUser(client);

        if (ret == RetCode_PaymentValiedate.Suc)
        {
            if (userServer == null)
            {
                code = ErrorCode.UserNotFound;
                err = $"cannot find user  :{client.userID}";
            }
            else
            {
                GoodsArche goodsArche = ConstData.Instance.GetGoods(validateData.goodsId);
                if (goodsArche != null)
                {
                    if (goodsArche.type == GoodsType.BuyDiamond)
                    {
                        ////发放水晶
                        int addDiamond = goodsArche.value;
                        //if (!userServer.data.hasCharged)
                        //{
                        //    addDiamond *= 2;
                        //    GameDebug.Log($"{userServer.data.id} {userServer.data.name} 首充双倍：{addDiamond}x2");
                        //}
                        //userServer.AddOneChargeTime();
                        userServer.AddDiamond(addDiamond);
                    }
                    else
                    {
                        GameDebug.LogError($"payment validate, goods type  invalid:{goodsArche.type}  buy.goodsId:{validateData.goodsId}");
                        err = "该商品类型无法支付购买";
                        code = RetCode_PaymentValiedate.GoodsCannotBuy;
                    }
                }
                else
                {
                    GameDebug.LogError($"goodsArche == null :{validateData.goodsId}");
                    err = $"cannot find goods with id:{validateData.goodsId}";
                    code = RetCode_PaymentValiedate.CannotFindGoods;
                }
            }
            if (save)
            {
                SavePayment(userServer.data.id, validateData);
            }
        }
        else
        {
            GameDebug.LogError($"支付验证失败  ret：{ret}  err:{failReason}");
        }
        PaymentValidateResponseData response = new PaymentValidateResponseData();
        response.goodsId = validateData.goodsId;
        //response.payType = validateData.payType;
        response.internalPid = validateData.productId;

        GameDebug.LogError($"支付验证结果  ret：{ret}     response.goodsId :{response.goodsId }");

        response.code = code;
        response.err = err;

        this.SendResponse(client, PaymentValidate_Key, this.m_MessageReceived.seq, response.Write());
    }

    /// <summary>
    /// 保存支付信息到数据库
    /// </summary>
    /// <param name="data"></param>
    void SavePayment(long uid,PaymentValidateData data)
    {
        payment table = new payment(uid,data.goodsId,data.productId ,data.payType,data.transactionId,""/*data.receipt*/);//receipt过长，不存储在数据库

        string database = users.GetUserDatabaseWithDeviceId(uid);

        long id = MysqlFunction.InsertIntoTable(database,SqlTable.payment, table);

        GameDebug.Log($"保存支付订单：{data.transactionId}  id:{id}  productId :{data.productId }");
    }

}


